package com.addzero.web.ui.hooks.tree.node_state

import com.addzero.web.ui.hooks.tree.TreeNode
import com.addzero.web.ui.hooks.tree.TreeSelectViewModel

/**
 *非叶子节点全选状态
 * @author zjarlin
 * @date 2025/04/03
 * @constructor 创建[NonLeafSelectedState]
 */
class NonLeafSelectedState : NodeState {
    override fun toggleSelection(node: TreeNode<*>, viewModel: TreeSelectViewModel<*>) {
        // 取消选中当前节点及其所有子节点
        val currentSelectedNodes = viewModel._selectedNodes.value
        viewModel._selectedNodes.value = currentSelectedNodes - node.id

        // 直接取消选中所有子节点，避免递归调用
        val childrenToDeselect = mutableSetOf<String>()
        collectAllChildrenIds(node, childrenToDeselect)
        viewModel._selectedNodes.value = viewModel._selectedNodes.value - childrenToDeselect
    }

    // 收集所有子节点ID
    private fun collectAllChildrenIds(node: TreeNode<*>, result: MutableSet<String>) {
        node.children.forEach { child ->
            result.add(child.id)
            collectAllChildrenIds(child, result)
        }
    }

    override fun toggleExpand(node: TreeNode<*>, viewModel: TreeSelectViewModel<*>) {
        viewModel.toggleNode(node.id)
    }
}
